package com.aimao.blog.service.impl;

import com.aimao.blog.service.KeyWordUseCount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Author PuaChen
 * @Create 2018-07-08 10:27
 */
@Service
public class KeyWordUseCountImpl implements KeyWordUseCount {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final static String WORKSPACE = "com.aimao.blog.service.impl.KeyWordUseCountImpl";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addKeyWord(String key) {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        //判断是否存在这个KEY
        if (opsForHash.hasKey(WORKSPACE, key)) {
            //如果存在的  进行加1操作
            opsForHash.increment(WORKSPACE, key, 1);
        } else {
            //如果不存在  存入这个KEY
            opsForHash.put(WORKSPACE, key, String.valueOf(1));
        }
    }

    @Override
    public Map<Object, Object> getAll() {
        if (stringRedisTemplate.hasKey(WORKSPACE)) {
            HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
            Map<Object, Object> map = opsForHash.entries(WORKSPACE);
            if (map.isEmpty()) {
                return null;
            }
            return map;
        }
        return null;
    }

    @Override
    public List<String> getHotList(int size) {
        List<String> res = new ArrayList<>();
        Map<Object, Object> map = getAll();
        if (map == null || map.isEmpty()) {
            return res;
        }
        List<Map.Entry<Object, Object>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            long v1 = Long.valueOf((String) o1.getValue());
            long v2 = Long.valueOf((String) o2.getValue());
            return (int) (v2 - v1);
        });
        int length = list.size() > size ? size : list.size();
        for (int i = 0; i < length; i++) {
            res.add((String) list.get(i).getKey());
        }
        return res;
    }
}
